<template>
    <div>
      
        <div>
            <a-input v-model:value="meetingStore.id" placeholder="请输入ID" />
            <a-input v-model:value="meetingStore.name" placeholder="请输入名称" />
            <a-button @click="login" type="primary">登录</a-button>
        </div>
        <div>
            <a-input v-model:value.trim="meetingStore.room" placeholder="请输入房间号" />
            <a-button @click="createRoom" type="primary">创建房间</a-button>
        </div>
        <div>
            <a-input v-model:value.trim="meetingStore.room" placeholder="请输入房间号" />
            <a-button @click="joinRoom" type="primary">加入房间</a-button>
        </div>
    </div>
</template>
<script setup lang="ts">
import { useMeetingStore } from '@/stores/meeting';
import { onMounted, onUnmounted } from 'vue';
import { createWebSocket, eventBus, sendMessage, MessageType, type Message } from './socket';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
const router = useRouter()
const meetingStore = useMeetingStore()
const onopen = () => {

}
const onclose = () => {

}
const onmessage = (event: any) => {
    
    const msg: Message = JSON.parse(event.data);
    // console.log("createRoom onmessage:")
    // console.log(msg)

    if (msg.code == 1) {
        message.error(msg.content)
        return
    }

    if (msg.messageType == MessageType.NOTICE) {
        message.success(msg.content)
    }

    if (msg.messageType == MessageType.CREATE_ROOM) {
        message.success("房间创建成功")
    }
    if (msg.messageType == MessageType.JOIN_ROOM) {
        
        router.push({
            path: '/meeting/room'
        })
    }

}
const login = () => {
    createWebSocket(meetingStore.id)
    eventBus.on("onopen", onopen)
    eventBus.on("onclose", onclose)
    eventBus.on("onmessage", onmessage)
}

const createRoom = () => {
    if (!meetingStore.room) {
        message.error("请输入房间号")
        return
    }
    sendMessage({
        messageType: MessageType.CREATE_ROOM,
        senderId: meetingStore.id + '',
        senderName: meetingStore.name + '',
        targetId: meetingStore.room + '',
        content: ''
    })
}

const joinRoom = () => {
    if (!meetingStore.room) {
        message.error("请输入房间号")
        return
    }
    sendMessage({
        messageType: MessageType.JOIN_ROOM,
        senderId: meetingStore.id + '',
        senderName: meetingStore.name + '',
        targetId: meetingStore.room + '',
        content: ''
    })
}

onMounted(() => {

    
    if(meetingStore.id){
        
        login()
    }
    
})

onUnmounted(() => {
    eventBus.off("onopen", onopen)
    eventBus.off("onclose", onclose)
    eventBus.off("onmessage", onmessage)
})
</script>